package com.shop.controller;

import com.shop.constant.MessageConstant;
import com.shop.entity.Result;
import com.shop.service.UserService;
import com.shop.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {
    @Reference
    private UserService userService;

    @PostMapping("/add")
    @ApiOperation("用户注册接口")
    public Result add(@RequestBody User user){
        if (userService.findUserName(user.getUsername())!=null){
            return new Result(false,MessageConstant.ADD_USER_FAIL);
        }else{
            userService.add(user);
            return new Result(true,MessageConstant.ADD_USER_SUCCESS);
        }
    }

    @GetMapping("/getUsername")
    @ApiOperation("获取当前用户名接口")
    public Result getUsername(){
        org.springframework.security.core.userdetails.User user= (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(user);
        if(user==null){
            return new Result(false,MessageConstant.QUERY_USER_FAIL);
        }
        String name=user.getUsername();
        return new Result(true,MessageConstant.QUERY_USER_SUCCESS,name);
    }

    @GetMapping("/getUserid")
    @ApiOperation("获取当前用户id接口")
    public Result getUserid(){
        org.springframework.security.core.userdetails.User user= (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(user==null){
            return new Result(false,MessageConstant.QUERY_USER_FAIL);
        }
        String name=user.getUsername();
        Integer uid = userService.getUserId(name);
        return new Result(true,MessageConstant.QUERY_USER_SUCCESS,uid);
    }

}
